package com.study.agp.paging;

import android.util.Log;
import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

public class MoviePageKeyDataSource extends PageKeyedDataSource<Integer, Movie> {
    private static final String TAG = "MoviePageKeyDataSource";
    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadInitial -> requestedLoadSize: %d, placeholdersEnabled: %s",
                params.requestedLoadSize, params.placeholdersEnabled);
        Log.i(TAG, paramsStr);

        // 计算需要加载几页数据
        int requestedLoadPage = Math.max(1, params.requestedLoadSize / PageConst.PAGE_SIZE);

        List<Movie> movieList = new LinkedList<>();
        // 只能加载整数页的数据
        for (int i = 0, loadSize = requestedLoadPage * PageConst.PAGE_SIZE; i < loadSize; i++) {
            movieList.add(new Movie("电影：" + i));
        }

        callback.onResult(movieList, requestedLoadPage, requestedLoadPage + 1);
    }

    @Override
    public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadBefore -> requestedLoadSize: %d, Key: %d",
                params.requestedLoadSize, params.key);
        Log.i(TAG, paramsStr);
        // loadInitial之后，接着调用loadBefore，询问是否还有更前面的数据未加载，如果有，后续RecycleView下滑展示更前面数据的时候，会调用loadBefore加载数据，直到没有更前面的数据为止
        // loadInitial是从第一页数据开始加载的，没有更前面的数据了，此处返回空数据，表示前面没有数据了
        callback.onResult(Collections.emptyList(), params.key);
    }

    @Override
    public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadAfter -> requestedLoadSize: %d, Key: %d",
                params.requestedLoadSize, params.key);
        Log.i(TAG, paramsStr);
        if(params.key > 10) {
            callback.onResult(Collections.emptyList(), 10);
            return;
        }
        int needLoadPageCount = params.requestedLoadSize / PageConst.PAGE_SIZE;
        // 加载包含当前key页及之后的数据
        int startPage = params.key;
        int endPage = startPage + needLoadPageCount;
        List<Movie> movieList = loadByPage(startPage, endPage, PageConst.PAGE_SIZE);
        callback.onResult(movieList, endPage);
    }

    private List<Movie> loadByPage(int startPageInclude, int endPageExclude, int pageSize) {
        int startIndex = (startPageInclude -1) * pageSize;
        int endIndex = (endPageExclude - 1) * pageSize;
        List<Movie> movieList = new LinkedList<>();
        for (int i = startIndex; i < endIndex; i++) {
            movieList.add(new Movie("电影：" + i));
        }
        return movieList;
    }
}
